<!--登录页面的vue2组件-->
<template>
  <div class="login-container">
    <div class="login-box">
      <h2>用户登录</h2>
      <form @submit.prevent="handleLogin">
        <div class="form-item">
          <input
            v-model="loginForm.username"
            type="text"
            placeholder="请输入用户名"
          >
        </div>
        <div class="form-item">
          <input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
          >
        </div>
        <div class="form-item">
          <button type="submit">登录</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
import {login} from "@/api/login";

export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        username: 'admin',
        password: '111111'
      },
      redirect: undefined,
      otherQuery: {}
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },

  methods: {
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    async handleLogin() {
      // 登录逻辑处理
      if (!this.loginForm.username || !this.loginForm.password) {
        this.$message.error('请输入用户名和密码')
        return
      }

      try {
        const {token} =  await login({
          username: this.loginForm.username,
          password: this.loginForm.password
        })
        console.log("this.redirect", this.redirect)
        this.$store.dispatch('user/login', {token}).then(()=>{
          this.$router.push({ path: this.redirect || '/', query: this.otherQuery }).catch((err) => {
            console.log("err",err)
          })
        })

      }catch (e) {
        console.log(e)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;

  .login-box {
    width: 400px;
    padding: 40px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);

    h2 {
      text-align: center;
      margin-bottom: 30px;
    }

    .form-item {
      margin-bottom: 20px;

      input {
        width: 100%;
        height: 40px;
        padding: 0 15px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;

        &:focus {
          border-color: #409eff;
          outline: none;
        }
      }

      button {
        width: 100%;
        height: 40px;
        background: #409eff;
        border: none;
        border-radius: 4px;
        color: #fff;
        font-size: 16px;
        cursor: pointer;

        &:hover {
          background: #66b1ff;
        }
      }
    }
  }
}
</style>
